package com.jrx.anytxn.param.job.updateRHBaseRate;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.config.RhBaseRateConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.dto.system.SystemParameterReq;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import com.jrx.anytxn.param.service.system.ISystemParameterService;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * @author 张靖烽
 * @description 读取文件更新人行利率
 * @createtime 2020-11-26 15:09
 */
@Configuration
public class UpdateRHBaseRateConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(UpdateRHBaseRateConfiguration.class);

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    @Autowired
    private RhBaseRateConfig rhBaseRateConfig;
    @Autowired
    private ISystemParameterService systemParameterService;
    @Resource
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;


    @Bean
    public Job updateRhBaseRateJob() {
        return jobBuilderFactory.get("updateRhBaseRateJob")
                .start(updateRhBaseRateStep())
                .build();
    }

    @Bean
    public Step updateRhBaseRateStep() {
        return stepBuilderFactory.get("updateRhBaseRateStep")
                .tasklet(updateRhBaseRateTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet updateRhBaseRateTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable prOrganizationTable = extPrOrganizationTableMapper.selectByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String date = DateFormatUtils.format(prOrganizationTable.getToday(), DateUtils.DATE_PATTERN_ANOTHER);
            String tenantId = prOrganizationTable.getTenantId();
            // 前置路径
            String path = rhBaseRateConfig.getFilePath() + File.separator + tenantId + File.separator + date + File.separator;
            // 文件路径
            String filePath = path + tenantId + "_CMIRTIRT_ALL_" + date + ".del";
            // ok文件路径
            String okFilePath = path + tenantId + "_CMIRTIRT_ALL_" + date + ".ok";
            logger.info("人行利率更新,文件路径：filePath：{}，okFilePath：{}", filePath, okFilePath);
            File file = new File(filePath);
            File okFile = new File(okFilePath);
            // 检查到文件次数
            int i = 0;
            // 文件检查结果
            boolean fileExistsFlag = false;
            while (i < 5 && !fileExistsFlag) {
                if (i > 0) {
                    Thread.sleep(1000 * 60 * 5);
                }
                fileExistsFlag = okFile.exists() && file.exists() && file.isFile();
                logger.info("人行利率更新,第{}次文件校验结果：{}", i + 1, fileExistsFlag);
                i++;
            }
            if (fileExistsFlag) {
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
                    String[] context;
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        line = line.trim();
                        if (line.length() <= 0) {
                            throw new Exception("存在为空的一行数据");
                        }
                        context = line.split("~@~");
                        String targetOrg = tenantId + "999999";
                        String number = context[0].trim();
                        String org = context[3].trim();
                        String amtType = context[5].trim();
                        String intrType = context[6].trim();
                        String rang = context[7].trim();
                        String effectiveDate = context[9].trim();
                        String intr = context[10].trim();
                        String preBusinessDate = DateFormatUtils.format(prOrganizationTable.getToday(), DateUtils.DATE_PATTERN_ANOTHER);
                        // 判断该行数据是否是人行利率，是则获取利率更新，不是则跳过（文件里只有一行数据符合要求）
                        boolean flag = tenantId.equals(number) && targetOrg.equals(org) && "01".equals(amtType) && "BB".equals(intrType) &&
                                "00".equals(rang) && preBusinessDate.compareTo(effectiveDate) >= 0;
                        if (flag) {
                            if (StringUtils.isNotBlank(intr)) {
                                intr = new BigDecimal(intr).divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP).toString();
                                // 构建更新请求数据
                                SystemParameterReq systemParameterReq = buildSystemParameterReq(tenantId, intr);
                                // 调用方法更新利率
                                systemParameterService.modifySystemParameter(systemParameterReq);
                                logger.info("人行利率更新成功，当前利率：{}", intr);
                            } else {
                                throw new Exception("人行利率为空");
                            }
                            break;
                        }
                    }
                } catch (Exception e) {
                    throw new Exception("更新人行利率异常");
                }
            } else {
                throw new Exception("未找到文件或文件不存在");
            }
            return RepeatStatus.FINISHED;
        };
    }

    private SystemParameterReq buildSystemParameterReq(String tenantId, String intr) {
        SystemParameterReq systemParameterReq = new SystemParameterReq();
        systemParameterReq.setParamCode("loan_prime_rate");
        systemParameterReq.setTenantId(tenantId);
        systemParameterReq.setParamDescription("人行利率");
        systemParameterReq.setParamValue(intr);
        systemParameterReq.setIsvalid("1");
        return systemParameterReq;
    }
}
